package com.example.xianji.activity;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.example.xianji.wxapi.WXEntryActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.UsersAPI;
import com.sina.weibo.sdk.openapi.models.User;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Main_LoginActivity extends Activity implements OnClickListener {
    public static int login_number;
    public static boolean qq_cancle_flag = false;
    public static boolean weixin_login_success = false;
    public static String openid, access_token;
    public static String wenxin_nickname, unionid, headimgurl;
    public boolean weibo_cancle = false;
    private RelativeLayout login_back;
    private TextView login_register_text, message_login, end_textview,
            start_textview;
    private Button login;
    private EditText edtitText_name, editText_password, login_editext_phone;
    private ProgressDialog mCustomProgressDialog;
    //    private SharedPreferences sp;
//    private Editor ed;
    private RelativeLayout wangji_mima, relativelayout_phone;
    private int end_loaction[], start_location[], zuihou_location[];
    private String openidString, qq_token;
    private boolean click_flag = false, third_log = false, weixin_flag = false;
    private ImageView qq_login, weibo_login, weixin_login;
    private SsoHandler mSsoHandler;
    private Oauth2AccessToken mAccessToken;
    private UsersAPI mUsersAPI;
    private String nickname, profile_image_url;
    private String APP_ID = "wx79e902dceb15b8bb";// 微信
    private String APP_SECRET = "31c11987ca6ad6014eef5f0caf93935d";
    private IWXAPI api;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (mCustomProgressDialog != null) {
                        mCustomProgressDialog.dismiss();
                        mCustomProgressDialog = null;
                    }
                    break;
                case 2:
                    /**
                     * 获取用户唯一标识
                     *
                     * @param openId
                     * @param accessToken
                     */
                    XJApplication.cachThreadPool.execute(new Runnable() {

                        @Override
                        public void run() {
                            getUID(openid, access_token);
                        }
                    });
                    break;
                case 3:
                    /**
                     * 第三方登录请求接口
                     */
                    XJApplication.cachThreadPool.execute(new Runnable() {

                        @Override
                        public void run() {
                            third_login(unionid, wenxin_nickname, headimgurl, "wx",
                                    access_token);
                            weixin_login_success = false;
                        }
                    });
                    break;
                case 0:
                    if (mCustomProgressDialog != null) {
                        mCustomProgressDialog.show();
                    }
                    break;
            }
        }
    };
    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                // qq登录
                JSONObject response = (JSONObject) msg.obj;
                qq_cancle_flag = false;
                if (response.has("nickname")) {
                    try {
                        String nicknameString = response.getString("nickname");
                        String image = response.getString("figureurl_qq_1");
                        third_login(openidString, nicknameString, image, "qq",
                                qq_token);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } else if (msg.what == 1) {

            } else if (msg.what == 2) {
                // 微博登录
                third_login(mAccessToken.getUid(), nickname, profile_image_url,
                        "sina", mAccessToken.getToken());
            }
        }
    };
    /**
     * 微博 OpenAPI 回调接口。 获取信息
     */
    private RequestListener mListener = new RequestListener() {
        @Override
        public void onComplete(String response) {
            if (!TextUtils.isEmpty(response)) {

                // 调用 User#parse 将JSON串解析成User对象
                User user = User.parse(response);
                if (user != null) {

                    nickname = user.screen_name;
                    profile_image_url = user.profile_image_url;
                    mHandler.sendEmptyMessage(2);
                } else {
                    Toast.makeText(Main_LoginActivity.this, response,
                            Toast.LENGTH_LONG).show();
                }
            }
        }

        @Override
        public void onWeiboException(WeiboException arg0) {
            Toast.makeText(Main_LoginActivity.this, arg0 + "",
                    Toast.LENGTH_LONG).show();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main__login);
        // XJApplication.getInstance().addActivity(this);
        login_back = (RelativeLayout) findViewById(R.id.login_relative_back);
        login_register_text = (TextView) findViewById(R.id.login_register_text);
        login = (Button) findViewById(R.id.login);
        edtitText_name = (EditText) findViewById(R.id.edtitText_name);
        editText_password = (EditText) findViewById(R.id.editText_password);
        editText_password.setTransformationMethod(PasswordTransformationMethod
                .getInstance());
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        wangji_mima = (RelativeLayout) findViewById(R.id.wangji_mima);
        message_login = (TextView) findViewById(R.id.message_login);
        end_textview = (TextView) findViewById(R.id.end_textview);
        start_textview = (TextView) findViewById(R.id.start_textview);
        login_editext_phone = (EditText) findViewById(R.id.login_editext_phone);
        qq_login = (ImageView) findViewById(R.id.qq_login);
        weibo_login = (ImageView) findViewById(R.id.weibo_login);
        weixin_login = (ImageView) findViewById(R.id.weixin_login);

        login_back.setOnClickListener(this);
        login_register_text.setOnClickListener(this);
        login.setOnClickListener(this);
        wangji_mima.setOnClickListener(this);
        message_login.setOnClickListener(this);
        qq_login.setOnClickListener(this);
        weibo_login.setOnClickListener(this);
        weixin_login.setOnClickListener(this);
    }

    /**
     * 动画位移
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        end_loaction = new int[2];
        start_location = new int[2];
        zuihou_location = new int[2];
        end_textview.getLocationInWindow(end_loaction);
        start_textview.getLocationInWindow(start_location);
        relativelayout_phone = (RelativeLayout) findViewById(R.id.relativelayout_phone);

        final ObjectAnimator animator1 = ObjectAnimator.ofFloat(start_textview,
                "translationY", end_loaction[1] - start_location[1]);
        final ValueAnimator animator = ValueAnimator.ofInt(20, 15);
        final LinearInterpolator inter = new LinearInterpolator();
        login_editext_phone.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.i("触摸触摸触摸", "触摸触摸触摸");
                // 触摸Edittext时发生位移动画及大小变化动画
                translation_anima(animator1, animator, inter, getResources()
                        .getColor(R.color.blue22));
                return false;
            }
        });

        login_editext_phone
                .setOnFocusChangeListener(new OnFocusChangeListener() {

                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        /**
                         * Edittext失去焦点时
                         */
                        if (!hasFocus) {
                            final ObjectAnimator Big_animator1 = ObjectAnimator
                                    .ofFloat(start_textview, "translationY", 0);
                            final ValueAnimator Big_animator = ValueAnimator
                                    .ofInt(15, 20);
                            // 触摸Edittext时发生位移动画及大小变化动画
                            translation_anima(Big_animator1, Big_animator,
                                    inter,
                                    getResources().getColor(R.color.black6));
                        }
                    }
                });
        relativelayout_phone.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    /*
                     * ObjectAnimator
                     * animator=ObjectAnimator.ofPropertyValuesHolder
                     * (start_textview,
                     * PropertyValuesHolder.ofFloat("scaleY",1f)
                     * ,PropertyValuesHolder
                     * .ofFloat("translationY",end_loaction[
                     * 1]-start_location[1]) );
                     */

                    // 触摸Edittext时发生位移动画及大小变化动画

                    translation_anima(animator1, animator, inter,
                            getResources().getColor(R.color.blue22));
                    /**
                     * 获取焦点，光标，键盘弹出
                     */
                    login_editext_phone.requestFocus();

                    InputMethodManager imm = (InputMethodManager) login_editext_phone
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                    return true;
                }
                return false;
            }
        });
    }

    private void translation_anima(ObjectAnimator animator1,
                                   ValueAnimator animator, LinearInterpolator inter, final int color) {
        animator.setInterpolator(inter);
        animator.setDuration(300);
        animator.start();
        animator1.setInterpolator(inter);
        animator1.setDuration(300);
        animator1.start();
        start_textview.getLocationInWindow(zuihou_location);

        animator.addUpdateListener(new AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                start_textview.setTextSize((Integer) animation
                        .getAnimatedValue());
                start_textview.setTextColor(color);
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.login_relative_back) {
            Main_LoginActivity.this.finish();

        } else if (v.getId() == R.id.login_register_text) {
            click_flag = false;
            Intent intent = new Intent(Main_LoginActivity.this,
                    Main_Regesiter_OneActivity.class);
            intent.putExtra("from", 1);
            startActivity(intent);

        } else if (v.getId() == R.id.login) {
            mCustomProgressDialog = new ProgressDialog(this);
            mCustomProgressDialog.setCanceledOnTouchOutside(false);
            mCustomProgressDialog.show();
            login();
        } else if (v.getId() == R.id.wangji_mima) {
            click_flag = false;
            startActivity(new Intent(Main_LoginActivity.this,
                    Main_Forget_PassWordActivity.class));

        } else if (v.getId() == R.id.message_login) {
            click_flag = false;
            Intent intent = new Intent(Main_LoginActivity.this,
                    Main_Message_LoginActivity.class);
            startActivityForResult(intent, Contant.dongtai_login_requestCode);
        } else if (v.getId() == R.id.weixin_login) {
            // 微信登录
            weixin_flag = true;
            api = WXAPIFactory.createWXAPI(this, APP_ID, true);
            api.registerApp(APP_ID);
            if (api != null && api.isWXAppInstalled()) {
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "xianji";
                api.sendReq(req);

            } else {
                Toast.makeText(this, "未安装微信", Toast.LENGTH_SHORT).show();
            }
        } else if (v.getId() == R.id.weibo_login) {
            // 微博登录
            click_flag = true;
            weibo_login();
        } else if (v.getId() == R.id.qq_login) {
            // QQ登录
            click_flag = true;
            Login_QQ();
        }
    }

    public void weibo_login() {
        mSsoHandler = new SsoHandler(Main_LoginActivity.this,
                XJApplication.mAuthInfo);
        // SSO 授权, 仅客户端
        mSsoHandler.authorizeClientSso(new AuthListener());

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Contant.dongtai_login_requestCode
                && resultCode == Contant.dongtai_login_success_back) {
            //从动态验证登录成功了
            if (PreferenceEngine.getInstance().getInt(Constant.SP.NAME, Constant.SP.KEY_NEWS_TO_LOGIN, 0) == Contant.NewsToLogin) {
                PreferenceEngine.getInstance().putInt(Constant.SP.NAME, Constant.SP.KEY_NEWS_TO_LOGIN, Contant.LoginToNews);//表明已经登录过了返回的新闻详情页面
            }
            Main_LoginActivity.this.finish();
        }
        /**
         * 微博回调
         */
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
        // QQ 还有最重要的是在onActivityResult（）方法中添加如下代码，不然调用完返回时会报错
        if (requestCode == Constants.REQUEST_LOGIN
                || requestCode == Constants.REQUEST_APPBAR) {
            Tencent.onActivityResultData(requestCode, resultCode, data,
                    new BaseUiListener());
        }

    }

    public void Login_QQ() {
        // 如果session无效，就开始登录
        XJApplication.getTencent().login(Main_LoginActivity.this, "all",
                new BaseUiListener());
    }

    /**
     * 第三方登录
     */
    public void third_login(String Uid, String nickname, String avatar,
                            String type, String token) {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();

        if (type.equals("sina")) {
            parms.addBodyParameter("origin_login", 60 + "");// 登录来源
        } else if (type.equals("qq")) {
            parms.addBodyParameter("origin_login", 61 + "");// 登录来源
        } else if (type.equals("wx")) {
            parms.addBodyParameter("origin_login", 59 + "");// 登录来源
        }
        parms.addBodyParameter("type_uid", Uid);
        parms.addBodyParameter("type", type);
        parms.addBodyParameter("oauth_token", token);
        parms.addBodyParameter("avatar", avatar);
        parms.addBodyParameter("nickname", nickname);

        httpUtils.send(HttpMethod.POST, Contant.third_Login, parms,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        Toast.makeText(Main_LoginActivity.this, "网络异常", Toast.LENGTH_SHORT)
                                .show();
                        if (mCustomProgressDialog != null) {
                            mCustomProgressDialog.dismiss();
                            mCustomProgressDialog = null;
                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        try {
                            JSONObject response = new JSONObject(arg0.result);
                            if (response.getInt("status") == 1) {
                                if (response.getInt("ismobile") > 0) {
                                    // 有手机号
                                    String token = response.getJSONObject(
                                            "data").getString("token");
                                    PreferenceEngine.getInstance().putBoolean(Constant.SP.NAME, Constant.SP.KEY_XIANJI_DENGLU, true);
                                    PreferenceEngine.getInstance().putString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, token);
                                    PreferenceEngine.getInstance().putInt(Constant.SP.NAME, Constant.SP.KEY_FINISH_FROM, 2);
                                    // 如果从登录页面登录成功后则设置为0，如果是点返回键回到"我的后台"则是1，得加载数据
                                    Contant.login_resume = 1;
                                    // 来自于服务详情页面的登录成功赋值为2
                                    if (Contant.come_from_fuwuDetail == 1) {
                                        Contant.come_from_fuwuDetail = 2;
                                    }
                                } else {
                                    // 没有手机号
                                    Toast.makeText(Main_LoginActivity.this,
                                            "登录成功,请编辑信息！", Toast.LENGTH_SHORT).show();
                                    if (response.getString("type").equals("FP")
                                            || response.getString("type")
                                            .equals("AP")) {
                                        // 个人用户跳转到个人编辑用户页面
                                        Intent intent = new Intent(
                                                Main_LoginActivity.this,
                                                Main_BianJi_XinxiActivity.class);
                                        intent.putExtra("xianji_token",
                                                response.getJSONObject("data")
                                                        .getString("token"));
                                        intent.putExtra("isMobile",
                                                Contant.not_mobile);
                                        Main_LoginActivity.this
                                                .startActivity(intent);
                                    } else {
                                        // 企业用户跳转到企业编辑页面
                                        Intent intent = new Intent(
                                                Main_LoginActivity.this,
                                                Main_Bianji_QiYe_InformationActivity.class);
                                        intent.putExtra("xianji_token",
                                                response.getJSONObject("data")
                                                        .getString("token"));
                                        intent.putExtra("isMobile",
                                                Contant.not_mobile);
                                        Main_LoginActivity.this
                                                .startActivity(intent);
                                    }
                                }
                                handler.sendEmptyMessage(1);
                                Main_LoginActivity.this.finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    public void login() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("origin_login",
                getIntent().getIntExtra("origin_login", 50) + "");
        parms.addBodyParameter("account", edtitText_name.getText().toString());
        parms.addBodyParameter("password", editText_password.getText()
                .toString());
        httpUtils.send(HttpMethod.POST, Contant.login, parms,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        handler.sendEmptyMessage(1);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        try {
                            JSONObject object = new JSONObject(arg0.result);
                            if (object.getInt("status") == 1) {
                                // login_number=1;
                                if (object.getInt("ismobile") > 0) {
                                    // 有手机号
                                    PreferenceEngine.getInstance().putBoolean(Constant.SP.NAME, Constant.SP.KEY_XIANJI_DENGLU, true);
                                    PreferenceEngine.getInstance().putString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN,
                                            object.getJSONObject("data").getString("token"));
                                    PreferenceEngine.getInstance().putInt(Constant.SP.NAME, Constant.SP.KEY_FINISH_FROM, 2);
                                    /*ed.putInt("my_xianji_set", 2);*/
                                    PreferenceEngine.getInstance().putString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TYPE,
                                            object.getString("type"));
                                    if (PreferenceEngine.getInstance().getInt(Constant.SP.NAME, Constant.SP.KEY_NEWS_TO_LOGIN, 0) == Contant.NewsToLogin) {
                                        PreferenceEngine.getInstance().putInt(Constant.SP.NAME, Constant.SP.KEY_NEWS_TO_LOGIN, Contant.LoginToNews);//表明已经登录过了返回的新闻详情页面
                                    }
                                    handler.sendEmptyMessage(1);
                                    //Contant.login_resume = 1;
                                    // 来自于服务详情页面的登录成功赋值为2
                                    if (Contant.come_from_fuwuDetail == 1) {
                                        Contant.come_from_fuwuDetail = 2;
                                    }
                                    // 如果从登录页面登录成功后则设置为0，如果是点返回键回到"我的后台"则是1，得加载数据
                                    Contant.change_password_login = 0;
                                    Main_LoginActivity.this.setResult(Contant.dongtai_login_success_back);
                                    Toast.makeText(Main_LoginActivity.this,
                                            object.getString("msg"), Toast.LENGTH_SHORT).show();
                                    Main_LoginActivity.this.finish();
                                } else {
                                    // 没有手机号
                                    Toast.makeText(Main_LoginActivity.this,
                                            "登录成功,请编辑信息！", Toast.LENGTH_SHORT).show();
                                    if (object.getString("type").equals("FP")
                                            || object.getString("type").equals(
                                            "AP")) {
                                        // 个人用户
                                        Intent intent = new Intent(
                                                Main_LoginActivity.this,
                                                Main_BianJi_XinxiActivity.class);
                                        intent.putExtra("xianji_token", object
                                                .getJSONObject("data")
                                                .getString("token"));
                                        intent.putExtra("isMobile",
                                                Contant.not_mobile);
                                        Main_LoginActivity.this
                                                .startActivity(intent);
                                    } else {
                                        // 企业用户
                                        Intent intent = new Intent(
                                                Main_LoginActivity.this,
                                                Main_Bianji_QiYe_InformationActivity.class);
                                        intent.putExtra("xianji_token", object
                                                .getJSONObject("data")
                                                .getString("token"));
                                        intent.putExtra("isMobile",
                                                Contant.not_mobile);
                                        Main_LoginActivity.this
                                                .startActivity(intent);
                                    }
                                    Main_LoginActivity.this.finish();
                                }
                            } else {
                                Toast.makeText(Main_LoginActivity.this,
                                        object.getString("msg"), 0).show();
                            }

                            handler.sendEmptyMessage(1);
                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (click_flag) {
            if (qq_cancle_flag == true || weibo_cancle == true
                    || third_log == false) {
            } else {
                if (Main_LoginActivity.this != null) {
                    handler.sendEmptyMessageDelayed(0, 1000);
                }
            }
        }

        if (weixin_flag && weixin_login_success) {
            if (Main_LoginActivity.this != null) {
                handler.sendEmptyMessageDelayed(0, 1000);
            }
            /**
             * 获取openid accessToken值用于后期操作 ssssqqqqq4444
             *
             * @param code
             *            请求码
             */
            XJApplication.cachThreadPool.execute(new Runnable() {

                @Override
                public void run() {
                    getResult(WXEntryActivity.code);

                }
            });
        }
    }

    /**
     * 获取openid accessToken值用于后期操作
     *
     * @param code 请求码
     */
    private void getResult(final String code) {
        final String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + APP_ID
                + "&secret="
                + APP_SECRET
                + "&code="
                + code
                + "&grant_type=authorization_code";
        XJApplication.cachThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                JsonObjectRequest request = new JsonObjectRequest(Method.GET,
                        path, null, new Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            openid = response.getString("openid")
                                    .toString().trim();
                            access_token = response
                                    .getString("access_token")
                                    .toString().trim();
                            handler.sendEmptyMessage(2);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                });
                XJApplication.getHttpQueues().cancelAll("abcPost");
                request.setTag("abcPost");
                request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1,
                        1.0f));
                XJApplication.getHttpQueues().add(request);
                XJApplication.getHttpQueues().start();
            }
        });
    }

    /**
     * 获取用户唯一标识
     *
     * @param openId
     * @param accessToken
     */
    private void getUID(final String openId, final String accessToken) {

        String path = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + accessToken + "&openid=" + openId;

        JsonObjectRequest request = new JsonObjectRequest(Method.GET, path,
                null, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    wenxin_nickname = response.getString("nickname");
                    unionid = response.getString("unionid");
                    headimgurl = response.getString("headimgurl");
                    handler.sendEmptyMessage(3);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    /**
     * 微博认证授权回调类。 1. SSO 授权时，需要在 {@link #onActivityResult} 中调用
     * {@link SsoHandler#authorizeCallBack} 后， 该回调才会被执行。 2. 非 SSO
     * 授权时，当授权结束后，该回调就会被执行。 当授权成功后，请保存该 access_token、expires_in、uid 等信息到
     * SharedPreferences 中。
     */
    class AuthListener implements WeiboAuthListener {
        @Override
        public void onComplete(Bundle values) {
            try {
                // try catch 解决 调用这个对象出现空指针异常 （兼容问题）
                // 从 Bundle 中解析 Token
                mAccessToken = Oauth2AccessToken.parseAccessToken(values);
                // 从这里获取用户输入的 电话号码信息
                String phoneNum = mAccessToken.getPhoneNum();
                String Uid = mAccessToken.getUid();
                mAccessToken.getRefreshToken();
                mAccessToken.getToken();
                if (mAccessToken.isSessionValid()) {

                    // 获取用户信息接口
                    mUsersAPI = new UsersAPI(Main_LoginActivity.this,
                            "4216978203", mAccessToken);
                    long uid = Long.parseLong(mAccessToken.getUid());

                    mUsersAPI.show(uid, mListener);

                    Toast.makeText(Main_LoginActivity.this, "授权成功",
                            Toast.LENGTH_SHORT).show();
                    weibo_cancle = false;
                } else {
                    // 以下几种情况，您会收到 Code：
                    // 1. 当您未在平台上注册的应用程序的包名与签名时；
                    // 2. 当您注册的应用程序包名与签名不正确时；
                    // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
                    String code = values.getString("code");
                    String message = "授权失败";
                    if (!TextUtils.isEmpty(code)) {
                        message = message + "\nObtained the code: " + code;
                    }
                    Toast.makeText(Main_LoginActivity.this, message,
                            Toast.LENGTH_LONG).show();
                }

            } catch (Exception e) {
            }
        }

        @Override
        public void onCancel() {
            Toast.makeText(Main_LoginActivity.this, "取消授权", Toast.LENGTH_LONG)
                    .show();
            weibo_cancle = true;
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(Main_LoginActivity.this, "请您先安装微博客户端！",
                    Toast.LENGTH_LONG).show();
        }
    }

    /**
     * QQ
     *
     * @author me
     */
    private class BaseUiListener implements IUiListener {

        @Override
        public void onCancel() {
            qq_cancle_flag = true;
            Toast.makeText(Main_LoginActivity.this, "取消授权", Toast.LENGTH_LONG)
                    .show();
        }

        @Override
        public void onComplete(Object arg0) {
            try {
                JSONObject jsonResponse = (JSONObject) arg0;
                if (null != jsonResponse && jsonResponse.length() == 0) {
                    Toast.makeText(Main_LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                    return;
                }
                third_log = true;
                openidString = ((JSONObject) arg0).getString("openid");
                qq_token = ((JSONObject) arg0).getString("access_token");
                XJApplication.mTencent.setAccessToken(qq_token,
                        ((JSONObject) arg0)
                                .getString(Constants.PARAM_EXPIRES_IN));
                XJApplication.mTencent.setOpenId(openidString);

                QQToken qqToken = XJApplication.mTencent.getQQToken();
                UserInfo info = new UserInfo(Main_LoginActivity.this, qqToken);
                info.getUserInfo(new IUiListener() {
                    @Override
                    public void onCancel() {
                    }

                    @Override
                    public void onComplete(final Object arg0) {
                        Message msg = new Message();
                        msg.obj = arg0;
                        msg.what = 0;
                        mHandler.sendMessage(msg);

                        new Thread() {

                            @Override
                            public void run() {
                                JSONObject json = (JSONObject) arg0;
                                // bitmap =
                                // Util.getbitmap(json.getString("figureurl_qq_2"));

                                Message msg = new Message();
                                // msg.obj = bitmap;
                                msg.what = 1;
                                mHandler.sendMessage(msg);
                            }
                        }.start();
                    }

                    @Override
                    public void onError(UiError arg0) {
                        Toast.makeText(Main_LoginActivity.this, "网络异常", Toast.LENGTH_SHORT)
                                .show();
                    }
                });

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError arg0) {
            third_log = false;
            Toast.makeText(Main_LoginActivity.this, "第三方登录异常！请重新登录！", Toast.LENGTH_SHORT).show();
        }
    }
}
